/* Tests for log.c
 *
 * Copyright 2008 Cian Synnott.
 * 
 * $Id: log_test.c 19 2009-11-27 20:46:48Z cian $
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "cutest/CuTest.h"
#include "log.h"

#define LOGFILE "testdata/test.log"
#define MESSAGE "This is a test log message"

#define BUFFER_SIZE 128

void TestLogging(CuTest *tc) {
  FILE *log_write;
  FILE *log_read;
  size_t num;
  char buffer[BUFFER_SIZE];
  char *date, *time, *level, *msg;

  log_write = fopen(LOGFILE, "w");
  if (log_write == NULL)
    CuFail(tc, "failed to open log file for writing");

  log_register(log_write);
  log_info(MESSAGE);
  fclose(log_write);

  log_read = fopen(LOGFILE, "r");
  if (log_read == NULL)
    CuFail(tc, "failed to open log file for reading");
  num = fread(&buffer, sizeof(char), BUFFER_SIZE, log_read);
  buffer[num] = 0;
  fclose(log_read);

  /* Some crude parsing ... */
  date = strtok(buffer, " ");
  time = strtok(NULL, " ");
  level = strtok(NULL, " ");
  msg = level + strlen(level) + 1;
  msg[strlen(msg) - 1] = 0;

  CuAssertStrEquals(tc, level, "INFO");
  CuAssertStrEquals(tc, MESSAGE, msg);

  if (unlink(LOGFILE))
    CuFail(tc, "failed to cleanup log file");
}

int main(void) {
  CuString *output = CuStringNew();
  CuSuite* suite = CuSuiteNew();

  SUITE_ADD_TEST(suite, TestLogging);

  CuSuiteRun(suite);
  CuSuiteSummary(suite, output);
  CuSuiteDetails(suite, output);
  printf("%s\n", output->buffer);

  return 0;
}
